package com.runa.rccprotocol.dto.runa;

import com.runa.protocol.dto.IResponseData;
import com.runa.protocol.dto.ModbusPoint;
import com.runa.protocol.util.ByteUtil;
import com.runa.protocol.util.DigitalUtil;
import com.runa.rccprotocol.dto.ConcentratorRequestData;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ModbusRequestData extends ConcentratorRequestData {

    private byte[] requestData;

    public ModbusRequestData() {
        this(null);
    }

    public ModbusRequestData(String serial) {
        super(serial);
        setHaveResult(true);
    }

    @Override
    public boolean check(IResponseData data) {
        return true;
    }

    @Override
    public byte[] getData() {
        return requestData;
    }

    public void setData(byte[] bytes) {
        this.requestData = bytes;
    }

    public void read(byte slaveId, byte functionCode, Integer address, Integer registerCount) {
        requestData = new byte[8];
        int index = 0;
        requestData[index++] = slaveId;
        requestData[index++] = functionCode;

        requestData[index++] = (byte)(address >> 8 & 0xff);
        requestData[index++] = (byte)(address & 0xff);

        requestData[index++] = (byte)(registerCount >> 8 & 0xff);
        requestData[index++] = (byte)(registerCount & 0xff);

        int crc = DigitalUtil.calcCrc16(requestData, 6);
        requestData[index++] = (byte) (crc & 0xff);
        requestData[index++] = (byte) (crc >> 8);
    }

    public void write(byte slaveId, byte functionCode, ModbusPoint modbusPoint) {
        int byteCount = modbusPoint.getByteCount();
        requestData = new byte[7 + byteCount + 2];
        int index = 0;
        requestData[index++] = slaveId;
        requestData[index++] = functionCode;

        requestData[index++] = (byte)(modbusPoint.getAddress() >> 8 & 0xff);
        requestData[index++] = (byte)(modbusPoint.getAddress() & 0xff);

        requestData[index++] = (byte)(modbusPoint.getRegisterCount() >> 8 & 0xff);
        requestData[index++] = (byte)(modbusPoint.getRegisterCount() & 0xff);

        // 字节数
        requestData[index++] = (byte)(byteCount & 0xff);

        for (byte byteValue : modbusPoint.getByteValues()) {
            requestData[index++] = byteValue;
        }

        int crc = DigitalUtil.calcCrc16(requestData, index);
        requestData[index++] = (byte) (crc & 0xff);
        requestData[index++] = (byte) (crc >> 8);

    }

    public static void main(String[] args) {
        String address = "145800984";
        int index = 196;
        int port = 4;
        RunaConcenRequestData requestData = new RunaConcenRequestData(address);
        ModbusRequestData modbusRequestData = new ModbusRequestData();
        modbusRequestData.read((byte)(index & 0xff), (byte)0x03, 1, 34);
        requestData.transparentForwarding(port, "2400", "E", 2, 20, modbusRequestData.getData());

        System.out.println(ByteUtil.byteToHexString(requestData.getData()));

    }
}
